package com.tianming.vrd.controller;

import com.tianming.vrd.entity.Product;
import com.tianming.vrd.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class ProductController {
    @Autowired(required = false)
    ProductMapper productMapper;

    @RequestMapping("/product/insert")
    public void insert(Product product, MultipartFile file) throws IOException {
        System.out.println("product = " + product + ", file = " + file);
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        //日期路径 yyyy年MM月dd日HH小时mm分ss秒
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");
        Date date = new Date();
        String datePath = format.format(date);

        String dirPath = "d:/upload";
        File dirFile = new File(dirPath + datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath + datePath + fileName;
        file.transferTo(new File(filePath));

        product.setUrl(datePath+fileName);

        productMapper.insert(product);
    }

    @RequestMapping("/product/select")
    public List<Product> select(){
        return productMapper.select();
    }
    @RequestMapping("/product/delete")
    public void delete(int id){
        productMapper.delete(id);
    }

    @RequestMapping("/product/selectbycid")
    public List<Product> selectByCid(int cid){
        System.out.println("cid = " + cid);
        return productMapper.selectByCid(cid);
    }

    @RequestMapping("/product/selectbywd")
    public List<Product> selectByWd(String wd){
        System.out.println("wd = " + wd);
        return productMapper.selectByWd(wd);
    }


    @RequestMapping("/product/selectbyview")
    public List<Product> selectByView(){
        return productMapper.selectByView();
    }

    @RequestMapping("/product/selectbylike")
    public List<Product> selectByLike(){
        return productMapper.selectByLike();
    }



}
